﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Transactions;

namespace FastShip88
{
    public partial class Combine : System.Web.UI.Page
    {
        DBAccess.UsersDataContext db;

        public List<int> SelectedParcels { 
            get {
                return ( List<int>) ViewState["SelectedParcels"] ; //.ToString().Split(new char[]{','});
            }

            set
            {
                ViewState["SelectedParcels"] = value;
            }
        }

        public List<int> SelectedSubs
        {
            get
            {
                return (List<int>)ViewState["SelectedSubs"]; //.ToString().Split(new char[]{','});
            }

            set
            {
                ViewState["SelectedSubs"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            db = new DBAccess.UsersDataContext();

            lblError.Visible = false;
            lblSuccess.Visible = false;
            if (!IsPostBack)
            {
                init_all();
            }

        }

        private void init_all()
        {
            SelectedParcels = new List<int>();
            SelectedSubs = new List<int>();

            init_parent_grid();
            init_sub_grid();

            Label lblId, lblWeight;
            TextBox txtDescription, txtDeclareValue, txtTariff;

            lblId = (Label)fvSelected.FindControl("lblId");
            lblWeight = (Label)fvSelected.FindControl("lblWeight");
            txtDescription = (TextBox)fvSelected.FindControl("txtDescription");
            txtDeclareValue = (TextBox)fvSelected.FindControl("txtDeclareValue");
            txtTariff = (TextBox)fvSelected.FindControl("txtTariff");

            if (null == lblId)
                return;

            lblId.Text = "";
            lblWeight.Text = "";
            txtDescription.Text = "";
            txtDeclareValue.Text = "";
            txtTariff.Text = "";

        }
       

        protected void init_parent_grid()
        {
            string strParcelNo = "";
            int userId = Utility.GetUserId(this);

            var parcels = from p in db.ParcelInfos
                          from s in db.ShopInfos
                          from ps in db.ParcelStatus
                          where p.ShopId == s.id && p.UserId == userId && p.StatusId == ps.id &&
                            p.ParcelNo.Contains(strParcelNo) && (p.StatusId == 10 || p.StatusId == 65 /*分拆取消*/ || p.StatusId == 75 /*合并取消*/  || p.StatusId == 95 /*中转请求取消*/ )    
                          select new { p.Id, p.UserId, p.ParcelNo, p.ShopId, s.name, p.Description, p.Weight, p.ArriveDate, StatusName = ps.name };

            gvResults.DataSourceID = null;
            gvResults.DataSource = parcels;
            gvResults.DataBind();

        }

        protected void init_sub_grid()
        {
            int userId = Utility.GetUserId(this);
            //TODO: 测试： 仅选出已经拆分完成的子包裹。
            var subparcels = from sp in db.SubParcels
                             where sp.ToId == null && sp.IsCancel == false && sp.ParcelInfo.UserId == userId && sp.ParcelInfo.StatusId ==60  /*分拆完成*/
                             select new { sp.Id, sp.Description, sp.Weight, sp.CreateDate, sp.FinishDate, ParcelNo = sp.ParcelInfo.ParcelNo };

            gvSub.DataSourceID = null;
            gvSub.DataSource = subparcels;
            gvSub.DataBind();

        }

        protected void btnCombine_Click(object sender, EventArgs e)
        {
            string strTempValue = string.Empty;

            int userId = Utility.GetUserId(this);

            Label lblId, lblWeight;
            TextBox txtDescription, txtDeclareValue, txtTariff;

            lblId =(Label) fvSelected.FindControl("lblId");
            lblWeight = (Label)fvSelected.FindControl("lblWeight");
            txtDescription = (TextBox)fvSelected.FindControl("txtDescription");
            txtDeclareValue = (TextBox)fvSelected.FindControl("txtDeclareValue");
            txtTariff = (TextBox)fvSelected.FindControl("txtTariff");

            using (TransactionScope ts = new TransactionScope())
            {
                var new_parcel = new DBAccess.ParcelInfo();

                new_parcel.Description = txtDescription.Text;
                new_parcel.UserId = userId;
                new_parcel.Weight = SafeConvert.ToDouble(lblWeight.Text);
                new_parcel.DeclareValue = (decimal) SafeConvert.ToDouble(txtDeclareValue.Text);
                new_parcel.Tariff = (decimal) SafeConvert.ToDouble(txtTariff.Text);
                new_parcel.StatusId = 77; /*新合并包裹*/
                new_parcel.ArriveDate = DateTime.Now;
                db.ParcelInfos.InsertOnSubmit(new_parcel);

                try
                {

                    db.SubmitChanges();

                    int new_pid = new_parcel.Id;

                    //foreach (GridViewRow gvr in gvResults.Rows)
                    //{
                    //    CheckBox cb = (CheckBox)gvr.FindControl("chkSelect"); // .Cells[0].Controls[0];
                    //    if (cb.Checked)
                    //    {
                    //        int pid = SafeConvert.ToInt(gvResults.DataKeys[gvr.RowIndex].Value.ToString());

                    //        var parcel = (from p in db.ParcelInfos
                    //                      where p.Id == pid
                    //                      select p).First();

                    //        parcel.StatusId = 50; //请求合并
                    //        parcel.ToId = new_pid;

                    //        db.SubmitChanges();

                    //    }
                    //}
                    foreach ( int pid in SelectedParcels)
                    {
                       
                            var parcel = (from p in db.ParcelInfos
                                          where p.Id == pid
                                          select p).First();

                            parcel.StatusId = 50; //请求合并
                            parcel.ToId = new_pid;

                            db.SubmitChanges();
                    }

                    //foreach (GridViewRow gvr in gvSub.Rows)
                    //{
                    //    CheckBox cb = (CheckBox)gvr.FindControl("chkSelect"); // .Cells[0].Controls[0];
                    //    if (cb.Checked)
                    //    {
                    //        int subid = SafeConvert.ToInt(gvSub.DataKeys[gvr.RowIndex].Value.ToString());

                    //        var sub_parcel = (from p in db.SubParcels
                    //                          where p.Id == subid
                    //                          select p).First();

                    //        sub_parcel.ToId = new_pid;

                    //        db.SubmitChanges();

                    //    }
                    //}
                    foreach (int pid in SelectedSubs)
                    {
                       
                            var sub_parcel = (from p in db.SubParcels
                                              where p.Id == pid
                                              select p).First();

                            sub_parcel.ToId = new_pid;

                            db.SubmitChanges();

                    }

                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    lblError.Visible = true;
                    
                    return;
                }
                    
                ts.Complete();

                lblId.Text = new_parcel.Id.ToString();
            }

            
            lblSuccess.Visible = true;
            lblSuccess.Text = lblSuccess.Text.Replace("%id", lblId.Text);

            init_all();

        }

        protected void gvResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvResults.PageIndex = e.NewPageIndex;
            init_parent_grid();
        }

        protected void gvSub_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvSub.PageIndex = e.NewPageIndex;
            init_sub_grid();
        }

        protected void CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            Label lblWeight;

            lblWeight = (Label)fvSelected.FindControl("lblWeight");

            CheckBox chk = sender as CheckBox;
            GridViewRow gr = chk.NamingContainer as GridViewRow;
            GridView  gv = gr.NamingContainer as GridView;
            double? _weight;
            double weight = SafeConvert.ToDouble(lblWeight.Text);


            if (gv.ID == "gvResults" )  //来自父包裹
            {
                int pid = SafeConvert.ToInt(gvResults.DataKeys[gr.RowIndex].Value);

                var parcel = (from p in db.ParcelInfos
                              where p.Id == pid
                              select p).First();
                _weight = parcel.Weight;
                if (null == _weight)
                    _weight = 0;

                if (chk.Checked)
                {
                    if (!SelectedParcels.Contains(pid))
                    {
                        SelectedParcels.Add(pid);
                        weight += _weight.Value;
                    }
                }
                else
                {
                    if (SelectedParcels.Contains(pid))
                    {
                        SelectedParcels.Remove(pid);
                        weight -= _weight.Value;
                    }
                }

            }
            else  //来自子包裹
            {
                int pid = SafeConvert.ToInt(gvSub.DataKeys[gr.RowIndex].Value);

                var sub_parcel = (from sp in db.SubParcels
                              where sp.Id == pid
                              select sp).First();

                _weight = sub_parcel.Weight;
                if (null == _weight)
                    _weight = 0;

                if (chk.Checked)
                {
                    if (!SelectedSubs.Contains(pid))
                    {
                        SelectedSubs.Add(pid);
                        weight += _weight.Value;
                    }
                }
                else
                {
                    if (SelectedSubs.Contains(pid))
                    {
                        SelectedSubs.Remove(pid);
                        weight -= _weight.Value;
                    }
                }
            }

            lblWeight.Text = weight.ToString("0.00");

        }

        protected void fvSelected_ModeChanging(object sender, FormViewModeEventArgs e)
        {
            e.NewMode = FormViewMode.Insert;
        }
    }
}
